package servlets;

import com.google.gson.Gson;
import entity.DormBuild;
import entity.ResponseData;
import utils.DBUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

@WebServlet({"/dorms", "/dorms/*"})
public class DormServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        handleCors(response);
        response.setContentType("application/json;charset=UTF-8");

        String pathInfo = request.getPathInfo();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtils.getConnection();

            if (pathInfo == null || pathInfo.equals("/")) {
                // 获取所有宿舍楼列表
                String sql = "SELECT * FROM t_dormbuild";
                pstmt = conn.prepareStatement(sql);
                rs = pstmt.executeQuery();

                List<DormBuild> dorms = new ArrayList<>();
                while (rs.next()) {
                    DormBuild dorm = new DormBuild(
                            rs.getInt("dormBuildId"),
                            rs.getString("dormBuildName"),
                            rs.getString("dormBuildUser")
                    );
                    dorms.add(dorm);
                }

                Gson gson = new Gson();
                String jsonResponse = gson.toJson(dorms);
                response.getWriter().write(jsonResponse);
            } else {
                // 获取特定宿舍楼详情
                String idStr = pathInfo.substring(1);
                try {
                    int dormId = Integer.parseInt(idStr);

                    String sql = "SELECT * FROM t_dormbuild WHERE dormBuildId = ?";
                    pstmt = conn.prepareStatement(sql);
                    pstmt.setInt(1, dormId);
                    rs = pstmt.executeQuery();

                    if (rs.next()) {
                        DormBuild dorm = new DormBuild(
                                rs.getInt("dormBuildId"),
                                rs.getString("dormBuildName"),
                                rs.getString("dormBuildUser")
                        );

                        Gson gson = new Gson();
                        String jsonResponse = gson.toJson(dorm);
                        response.getWriter().write(jsonResponse);
                    } else {
                        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                        Gson gson = new Gson();
                        String jsonResponse = gson.toJson(new ResponseData(false, "宿舍楼未找到"));
                        response.getWriter().write(jsonResponse);
                    }
                } catch (NumberFormatException e) {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    Gson gson = new Gson();
                    String jsonResponse = gson.toJson(new ResponseData(false, "无效的宿舍ID"));
                    response.getWriter().write(jsonResponse);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            Gson gson = new Gson();
            response.getWriter().write(gson.toJson(new ResponseData(false, "服务器错误")));
        } finally {
            DBUtils.close(conn, pstmt, rs);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        handleCors(response);
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        StringBuilder jsonBuilder = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                jsonBuilder.append(line);
            }
        }

        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            Gson gson = new Gson();
            DormBuild newDorm = gson.fromJson(jsonBuilder.toString(), DormBuild.class);

            // 检查必要字段
            if (newDorm.getDormBuildName() == null || newDorm.getDormBuildUser() == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().write(gson.toJson(new ResponseData(false, "宿舍楼名称和管理员不能为空")));
                return;
            }

            String sql = "INSERT INTO t_dormbuild (dormBuildName, dormBuildUser) VALUES (?, ?)";
            conn = DBUtils.getConnection();
            pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pstmt.setString(1, newDorm.getDormBuildName());
            pstmt.setString(2, newDorm.getDormBuildUser());

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) {
                    if (generatedKeys.next()) {
                        newDorm.setDormBuildId(generatedKeys.getInt(1));
                    }
                }
                response.getWriter().write(gson.toJson(new ResponseData(true, "宿舍楼添加成功")));
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write(gson.toJson(new ResponseData(false, "添加失败")));
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Gson gson = new Gson();
            response.getWriter().write(gson.toJson(new ResponseData(false, "请求数据格式错误")));
        } finally {
            DBUtils.close(conn, pstmt, null);
        }
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        handleCors(response);
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        String pathInfo = request.getPathInfo();
        if (pathInfo == null || pathInfo.equals("/")) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Gson gson = new Gson();
            response.getWriter().write(gson.toJson(new ResponseData(false, "必须指定宿舍ID")));
            return;
        }

        String idStr = pathInfo.substring(1);
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            int dormId = Integer.parseInt(idStr);

            StringBuilder jsonBuilder = new StringBuilder();
            try (BufferedReader reader = request.getReader()) {
                String line;
                while ((line = reader.readLine()) != null) {
                    jsonBuilder.append(line);
                }
            }

            Gson gson = new Gson();
            DormBuild updatedDorm = gson.fromJson(jsonBuilder.toString(), DormBuild.class);

            String sql = "UPDATE t_dormbuild SET dormBuildName = ?, dormBuildUser = ? WHERE dormBuildId = ?";
            conn = DBUtils.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, updatedDorm.getDormBuildName());
            pstmt.setString(2, updatedDorm.getDormBuildUser());
            pstmt.setInt(3, dormId);

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                response.getWriter().write(gson.toJson(new ResponseData(true, "宿舍楼信息更新成功")));
            } else {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().write(gson.toJson(new ResponseData(false, "宿舍楼未找到")));
            }
        } catch (NumberFormatException e) {
        } catch (Exception e) {
        }
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        handleCors(response);
        response.setContentType("application/json;charset=UTF-8");

        String pathInfo = request.getPathInfo();
        if (pathInfo == null || pathInfo.equals("/")) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Gson gson = new Gson();
            response.getWriter().write(gson.toJson(new ResponseData(false, "必须指定宿舍ID")));
            return;
        }

        String idStr = pathInfo.substring(1);
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            int dormId = Integer.parseInt(idStr);

            String sql = "DELETE FROM t_dormbuild WHERE dormBuildId = ?";
            conn = DBUtils.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, dormId);

            int affectedRows = pstmt.executeUpdate();

            Gson gson = new Gson();
            if (affectedRows > 0) {
                response.getWriter().write(gson.toJson(new ResponseData(true, "宿舍楼删除成功")));
            } else {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().write(gson.toJson(new ResponseData(false, "宿舍楼未找到")));
            }
        } catch (NumberFormatException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Gson gson = new Gson();
            response.getWriter().write(gson.toJson(new ResponseData(false, "无效的宿舍ID")));
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            Gson gson = new Gson();
            response.getWriter().write(gson.toJson(new ResponseData(false, "服务器错误")));
        } finally {
            DBUtils.close(conn, pstmt, null);
        }
    }

    @Override
    protected void doOptions(HttpServletRequest request, HttpServletResponse response) {
        handleCors(response);
        response.setStatus(HttpServletResponse.SC_OK);
    }

    private void handleCors(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Custom-Header");
    }
}